package ar.edu.caece.compiler.grammar.factories;

import ar.edu.caece.compiler.grammar.AbstractTokenVisitorFactory;
import ar.edu.caece.compiler.grammar.GrammarSymbol;
import ar.edu.caece.compiler.grammar.TokenVisitorInterface;
import ar.edu.caece.compiler.grammar.nonterminals.EXPR;
import ar.edu.caece.compiler.grammar.nonterminals.EXPR2;
import ar.edu.caece.compiler.grammar.nonterminals.EXPRA;
import ar.edu.caece.compiler.grammar.terminals.GrammarTerminal;
import ar.edu.caece.compiler.model.LexicalAnalyzer;

public class EXPRFactory extends AbstractTokenVisitorFactory {

	private static EXPRFactory INSTANCE;
	
	private EXPR2Factory expr2Factory;
	private EXPRAFactory expraFactory;
	private TokenVisitorInterface parseEXPR2;
	private TokenVisitorInterface parseEXPRA;
	
	public static EXPRFactory getInstance() throws Exception {
		if(INSTANCE==null) INSTANCE = new EXPRFactory();
		return INSTANCE;
	}
	
	public static EXPRFactory getInstance(LexicalAnalyzer analizadorLexico) throws Exception {
		if(INSTANCE==null) INSTANCE = new EXPRFactory(analizadorLexico);
		return INSTANCE;
	}
	
	private Initializer initializer = new Initializer() {
		
		@Override
		public void init() throws Exception {
			initializer = NoOperationInitializer.getInstance();
			expr2Factory = EXPR2Factory.getInstance();
			expraFactory = EXPRAFactory.getInstance();
			parseEXPR2 = expr2Factory.makeVisitor();
			parseEXPRA = expraFactory.makeVisitor();
		}
	};
	
	private EXPRFactory() throws Exception {

	}
	
	public EXPRFactory(LexicalAnalyzer analizadorLexico) {
		super(analizadorLexico);
	}

	@Override
	public TokenVisitorInterface makeChainedVisitor(
			final TokenVisitorInterface siguiente) throws Exception {
		initializer.init();

		return new TokenVisitorInterface() {

			@Override
			public GrammarSymbol defaultCase(GrammarTerminal llamador)
					throws Exception {
				GrammarSymbol result = llamador.execute(expr2Factory.makeChainedVisitor(siguiente));
				if(result instanceof EXPR2) {
					return new EXPR ((EXPR2) result, (EXPRA) nextToken().execute(parseEXPRA)); 
				} 
				else {
					return result;
				}
			}
			
		};
	
	}
	@Override
	public TokenVisitorInterface makeVisitor() throws Exception {
		initializer.init();

		return new TokenVisitorInterface() {

			@Override
			public GrammarSymbol defaultCase(GrammarTerminal llamador)
					throws Exception {
					return new EXPR ((EXPR2) llamador.execute(parseEXPR2), (EXPRA) nextToken().execute(parseEXPRA)); 
			}
		};
	}
	
	
}
